<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>消息盒子</title>
    <link rel="stylesheet" href="../../../layui.css">
    <style>
        .layim-msgbox {
            margin: 15px;
        }

        .layim-msgbox li {
            position: relative;
            margin-bottom: 10px;
            padding: 0 130px 10px 60px;
            padding-bottom: 10px;
            line-height: 22px;
            border-bottom: 1px dotted #e2e2e2;
        }

        .layim-msgbox .layim-msgbox-tips {
            margin: 0;
            padding: 10px 0;
            border: none;
            text-align: center;
            color: #999;
        }

        .layim-msgbox .layim-msgbox-system {
            padding: 0 10px 10px 10px;
        }

        .layim-msgbox li p span {
            padding-left: 5px;
            color: #999;
        }

        .layim-msgbox li p em {
            font-style: normal;
            color: #FF5722;
        }

        .layim-msgbox-avatar {
            position: absolute;
            left: 0;
            top: 0;
            width: 50px;
            height: 50px;
        }

        .layim-msgbox-user {
            padding-top: 5px;
        }

        .layim-msgbox-content {
            margin-top: 3px;
        }

        .layim-msgbox .layui-btn-small {
            padding: 0 15px;
            margin-left: 5px;
        }

        .layim-msgbox-btn {
            position: absolute;
            right: 0;
            top: 12px;
            color: #999;
        }
    </style>
</head>
<body>

<ul class="layim-msgbox" id="LAY_view"></ul>

<div style="margin: 0 15px;display: none">
    <blockquote class="layui-elem-quote">注意：这些都是模拟数据，实际使用时，需将其中的模拟接口改为你的项目真实接口。
        <br>该模版文件所在目录（相对于layui.js）：/css/modules/layim/html/msgbox.html
    </blockquote>
</div>

<textarea title="消息模版" id="LAY_tpl" style="display:none;">
{{# layui.each(d.data, function(index, item){
  if(item.fromUserId == d.userId){ }}
    <li >
      <a href="javascript:void(0)" target="_blank">
        <img src="{{ item.toUser.headLogo }}" class="layui-circle layim-msgbox-avatar">
      </a>
      <p class="layim-msgbox-user">
        <a href="javascript:void(0)" target="_blank">{{ item.toUser.userName||'' }}</a>
        <span>{{ layui.util.toDateString(item.sendTime, 'yyyy-MM-dd HH:mm:ss') }}</span>
      </p>
      <p class="layim-msgbox-content">
        申请添加对方为好友
        <span>{{ item.postMessage ? '附言: '+item.postMessage : '' }}</span>
      </p>
      <p class="layim-msgbox-btn">
          {{# if(item.status == 1){ }}
          等待验证
          {{# }else if(item.status == 2){ }}
          已同意你的好友申请
          {{# }else{ }}
          已拒绝你的好友申请
          {{# } }}
      </p>
    </li>
  {{# } else { }}
    <li data-uid="{{ item.fromUserId }}" data-toid="{{ item.toUserId }}" data-fromgroup="{{ item.fromGroupId }}">
      <a href="javascript:void(0)" target="_blank">
        <img src="{{ item.user.headLogo }}" class="layui-circle layim-msgbox-avatar">
      </a>
      <p class="layim-msgbox-user">
        <a href="javascript:void(0)" target="_blank">{{ item.user.userName||'' }}</a>
        <span>{{ layui.util.toDateString(item.sendTime, 'yyyy-MM-dd HH:mm:ss') }}</span>
      </p>
      <p class="layim-msgbox-content">
        申请添加你为好友
        <span>{{ item.postMessage ? '附言: '+item.postMessage : '' }}</span>
      </p>
      <p class="layim-msgbox-btn">
          {{# if(item.status == 1){ }}
            <button class="layui-btn layui-btn-small" data-type="agree">同意</button>
            <button class="layui-btn layui-btn-small layui-btn-primary" data-type="refuse">拒绝</button>
          {{# }else if(item.status == 2){ }}
          已同意
          {{# }else{ }}
          已拒绝
          {{# } }}
      </p>
    </li>
  {{# }
}); }}
</textarea>
<script src="../../../../layui.all.js"></script>
<script>
    layui.use(['layim', 'flow'], function () {
        var layim = layui.layim
            , layer = layui.layer
            , laytpl = layui.laytpl
            , $ = layui.jquery
            , flow = layui.flow;
        var token = layui.sessionData('nepadmin', 'token');
        // 用于临时记录请求到的数据
        var cache = {};
        //请求消息
        var renderMsg = function (page, callback) {
            // 实际部署时，请将下述 getmsg.js 改为你的接口地址
            $.get('/chat/messages/page', {
                current: page || 1,
                size: 5,
                token: token
            }, function (res) {
                if (res.code != 0) {
                    return layer.msg(res.msg);
                }
                //记录来源用户信息
                layui.each(res.data, function (index, item) {
                    cache[item.fromUserId] = item.user;
                });
                callback && callback(res.data,res.userId, res.pages);
            });
        };
        //消息信息流
        flow.load({
            elem: '#LAY_view' //流加载容器
            , isAuto: false
            , end: '<li class="layim-msgbox-tips">暂无更多新消息</li>'
            , done: function (page, next) { //加载下一页
                renderMsg(page, function (data, userId,pages) {
                    var html = laytpl(LAY_tpl.value).render({
                        data: data
                        , page: page
                        , userId : userId
                    });
                    next(html, page < pages);
                });
            }
        });

        //操作
        var active = {
            //同意
            agree: function (othis) {
                var li = othis.parents('li')
                    , uid = li.data('uid')
                    , toid = li.data('toid')
                    , from_group = li.data('fromgroup')
                    , user = cache[uid];
                // 查询出该用户的分组
                var groupArr = [];
                $.ajaxSettings.async = false;
                $.get('/chat/friendsGroups/list', {token:token}, function (res) {
                    if (res.code != 0) {
                        return layer.msg(res.msg);
                    }
                    $.each(res.data, function (index, value) {
                        groupArr.push({id: value.id, groupname: value.name});
                    })
                });
                $.ajaxSettings.async = true;
                //选择分组
                console.log(from_group);
                parent.layui.layim.setFriendGroup({
                    type: 'friend'
                    , username: user.userName
                    , avatar: user.headLogo
                    , group: groupArr //获取好友分组数据
                    , submit: function (group, index) {
                        var friendData = {
                            friendId: uid //对方用户ID
                            , targetGroupId: from_group //对方设定的好友分组
                            , friendGroupId: group //我设定的好友分组
                        };
                        $.ajax({
                            type: 'POST',
                            url: '/chat/friends/save',
                            contentType: "application/json",
                            data:JSON.stringify(friendData),
                            headers: {
                                "token": token
                            },
                            success: function (res) {
                                if (res.code != 0) {
                                    //return layer.msg(res.msg);
                                    parent.layer.close(index);
                                    layer.msg(res.msg);
                                    return;
                                }
                                //将好友追加到主面板
                                parent.layui.layim.addList({
                                    type: 'friend'
                                    , avatar: user.headLogo //好友头像
                                    , username: user.userName //好友昵称
                                    , groupid: group //所在的分组id
                                    , id: uid //好友ID
                                    , sign: user.remark //好友签名
                                });
                                parent.layer.close(index);
                                othis.parent().html('已同意');
                                parent.layui.im.contextMenu();//更新右键点击事件
                                // 通知对方已加为好友
                                var sendContent = {fromId:toid+"",toId:uid+"",toGroupId:from_group+"",agreeFriend:'1'};
                                parent.layui.im.sendMessage(JSON.stringify(sendContent));
                            }
                        });
                    }
                });
            }
            //拒绝
            , refuse: function (othis) {
                var li = othis.parents('li')
                    , uid = li.data('uid')
                    , toid = li.data('toid');
                layer.confirm('确定拒绝吗？', function (index) {
                    $.post('/chat/messages/refuse/'+uid, {
                        _method: 'PUT'
                    }, function (res) {
                        if (res.code != 0) {
                            return layer.msg(res.msg);
                        }
                        layer.close(index);
                        othis.parent().html('<em>已拒绝</em>');

                        // 通知对方已拒绝
                        var sendContent = {toId:uid+"",refuseFriend:'1'};
                        parent.layui.im.sendMessage(JSON.stringify(sendContent));
                    });
                });
            }
        };

        $('body').on('click', '.layui-btn', function () {
            var othis = $(this), type = othis.data('type');
            active[type] ? active[type].call(this, othis) : '';
        });
    });
</script>
</body>
</html>
